/* 多线程操作 */
const { Worker } = require('worker_threads');
// 要求：Node版本 >= 10.5.0
class Threads {
  /**
   * 构造函数
   * @param {*} workers 线程池，示例：
   * [
   *   {
   *     script: '../inspectExe/workers/xxx.js',
   *     threadId: 'xxx'
   *   }
   * ]
   */
  constructor(workers = []) {
    // Worker线程池
    this._workers = [];
    workers.length && this._initWorkers(workers);
  }

  // 初始化创建Worker线程池
  _initWorkers(workers) {
    workers.forEach(item => {
      const worker = new Worker(item.script);
      // 设置线程标识符属性
      worker.threadId = item.threadId;
      // 监听每个线程的消息事件
      worker.on('message', (message) => {
        console.log(`Received message from worker thread ${worker.threadId}:`, message);
      });
      // 存储线程实例到数组
      this._workers.push(worker);
    });
  }

  // 终止所有线程
  terminateAllThreads() {
    for (const worker of this._workers) {
      worker.terminate();
      console.log(`Terminated worker thread ${worker.threadId}`);
    }
  }
}
module.exports = Threads;
